package com.ruoyi.point.service.impl;

import java.util.List;
import java.util.Date;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.point.mapper.ExchangeOrderMapper;
import com.ruoyi.point.mapper.UsersMapper;
import com.ruoyi.point.mapper.PointFlowMapper;
import com.ruoyi.point.domain.ExchangeOrder;
import com.ruoyi.point.domain.Users;
import com.ruoyi.point.domain.PointFlow;
import com.ruoyi.point.service.IExchangeOrderService;

/**
 * 兑换订单Service业务层处理
 * 
 * @author hy
 * @date 2025-08-12
 */
@Service
public class ExchangeOrderServiceImpl implements IExchangeOrderService 
{
    @Autowired
    private ExchangeOrderMapper exchangeOrderMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    @Qualifier("pointFlowMapper1")
    private PointFlowMapper pointFlowMapper;

    /**
     * 查询兑换订单
     * 
     * @param id 兑换订单主键
     * @return 兑换订单
     */
    @Override
    public ExchangeOrder selectExchangeOrderById(Long id)
    {
        return exchangeOrderMapper.selectExchangeOrderById(id);
    }

    /**
     * 查询兑换订单列表
     * 
     * @param exchangeOrder 兑换订单
     * @return 兑换订单
     */
    @Override
    public List<ExchangeOrder> selectExchangeOrderList(ExchangeOrder exchangeOrder)
    {
        return exchangeOrderMapper.selectExchangeOrderList(exchangeOrder);
    }

    /**
     * 新增兑换订单
     * 
     * @param exchangeOrder 兑换订单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertExchangeOrder(ExchangeOrder exchangeOrder)
    {
        // 设置默认状态为处理中
        exchangeOrder.setDefaultStatus();
        
        int result = exchangeOrderMapper.insertExchangeOrder(exchangeOrder);
        // 不再需要清除缓存
        return result;
    }

    /**
     * 修改兑换订单
     * 
     * @param exchangeOrder 兑换订单
     * @return 结果
     */
    @Override
    public int updateExchangeOrder(ExchangeOrder exchangeOrder)
    {
        int result = exchangeOrderMapper.updateExchangeOrder(exchangeOrder);
        if (result > 0) {
            // 清除相关缓存
            // clearExchangeOrderCache(exchangeOrder.getUserId()); // 移除缓存清除
            // clearExchangeOrderDetailCache(exchangeOrder.getId()); // 移除缓存清除
            // 清除所有订单详情缓存，因为前端调用的是 selectAllExchangeOrderDetails
            // clearAllExchangeOrderDetailsCache(); // 移除缓存清除
        }
        return result;
    }

    /**
     * 批量删除兑换订单
     * 
     * @param ids 需要删除的兑换订单主键集合
     * @return 结果
     */
    @Override
    public int deleteExchangeOrderByIds(Long[] ids)
    {
        int result = exchangeOrderMapper.deleteExchangeOrderByIds(ids);
        if (result > 0) {
            // 清除相关缓存
            // for (Long id : ids) { // 移除缓存清除
            //     clearExchangeOrderDetailCache(id);
            // }
            // 清除所有订单详情缓存，因为批量删除订单会影响列表
            // clearAllExchangeOrderDetailsCache(); // 移除缓存清除
        }
        return result;
    }

    /**
     * 删除兑换订单信息
     * 
     * @param id 兑换订单主键
     * @return 结果
     */
    @Override
    public int deleteExchangeOrderById(Long id)
    {
        int result = exchangeOrderMapper.deleteExchangeOrderById(id);
        if (result > 0) {
            // clearExchangeOrderDetailCache(id); // 移除缓存清除
            // 清除所有订单详情缓存，因为删除订单会影响列表
            // clearAllExchangeOrderDetailsCache(); // 移除缓存清除
        }
        return result;
    }

    /**
     * 根据ID查询兑换订单详情（多表联查）
     * 
     * @param id 兑换订单ID
     * @return 兑换订单详情
     */
    @Override
    public ExchangeOrder selectExchangeOrderDetailById(Long id)
    {
        // 直接从数据库查询，不使用缓存
        return exchangeOrderMapper.selectExchangeOrderDetailById(id);
    }

    /**
     * 查询兑换订单详情（多表联查）
     * 
     * @param id 兑换订单ID
     * @return 兑换订单详情
     */
    @Override
    public ExchangeOrder selectExchangeOrderDetail(Long id)
    {
        return exchangeOrderMapper.selectExchangeOrderDetail(id);
    }

    /**
     * 查询所有兑换订单详情（多表联查）
     * 
     * @return 所有兑换订单详情列表
     */
    @Override
    public List<ExchangeOrder> selectAllExchangeOrderDetails()
    {
        // 直接从数据库查询，不使用缓存
        return exchangeOrderMapper.selectAllExchangeOrderDetails();
    }

    /**
     * 查询所有处理中的订单（多表联查）
     * 
     * @return 处理中订单列表
     */
    @Override
    public List<ExchangeOrder> selectProcessingOrders()
    {
        // 直接从数据库查询，不使用缓存
        return exchangeOrderMapper.selectProcessingOrders();
    }

    /**
     * 查询用户兑换订单历史列表（多表联查）
     * 
     * @param userId 用户ID
     * @return 兑换订单历史列表
     */
    @Override
    public List<ExchangeOrder> selectExchangeOrderHistoryByUserId(Long userId)
    {
        // 直接从数据库查询，不使用缓存
        return exchangeOrderMapper.selectExchangeOrderHistoryByUserId(userId);
    }

    /**
     * 查询兑换订单历史列表（多表联查，支持分页和筛选）
     * 
     * @param exchangeOrder 查询条件
     * @return 兑换订单历史列表
     */
    @Override
    public List<ExchangeOrder> selectExchangeOrderHistoryList(ExchangeOrder exchangeOrder)
    {
        return exchangeOrderMapper.selectExchangeOrderHistoryList(exchangeOrder);
    }

    /**
     * 创建兑换订单并扣减用户积分
     * 
     * @param exchangeOrder 兑换订单信息
     * @return 创建结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ExchangeOrder createExchangeOrderWithPointDeduction(ExchangeOrder exchangeOrder) {
        // 1. 验证用户积分是否足够
        Users user = usersMapper.selectUsersById(exchangeOrder.getUserId().intValue());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        if (user.getTotalPoint() == null || user.getTotalPoint() < exchangeOrder.getPoint()) {
            throw new RuntimeException("用户积分不足，当前积分：" + user.getTotalPoint() + "，需要积分：" + exchangeOrder.getPoint());
        }
        
        // 2. 生成订单号
        String orderSn = generateOrderSn();
        exchangeOrder.setOrderSn(orderSn);
        
        // 3. 设置订单默认状态
        exchangeOrder.setDefaultStatus();
        
        // 4. 插入订单
        int orderResult = exchangeOrderMapper.insertExchangeOrder(exchangeOrder);
        if (orderResult <= 0) {
            throw new RuntimeException("创建订单失败");
        }
        
        // 5. 扣减用户积分
        Long newBalance = user.getTotalPoint() - exchangeOrder.getPoint();
        Users updateUser = new Users();
        updateUser.setId(user.getId());
        updateUser.setTotalPoint(newBalance);
        int userResult = usersMapper.updateUsers(updateUser);
        if (userResult <= 0) {
            throw new RuntimeException("扣减用户积分失败");
        }
        
        // 6. 记录积分流水
        PointFlow pointFlow = new PointFlow();
        pointFlow.setId(System.currentTimeMillis()); // 使用时间戳作为ID
        pointFlow.setUserId(exchangeOrder.getUserId()); // 直接使用Long类型
        pointFlow.setPoint(-exchangeOrder.getPoint()); // 负数表示扣减
        pointFlow.setRuleId(2L); // 积分规则ID，设置为固定值2表示兑换订单
        pointFlow.setBalance(newBalance);
        pointFlow.setDescription("兑换商品：" + exchangeOrder.getGoodsName() + "，订单号：" + orderSn);
        pointFlow.setDel(0);
        pointFlow.setCreateTime(new Date());
        
        int flowResult = pointFlowMapper.insertPointFlow(pointFlow);
        if (flowResult <= 0) {
            throw new RuntimeException("记录积分流水失败");
        }
        
        // 7. 清除相关缓存
        // clearExchangeOrderCache(exchangeOrder.getUserId()); // 移除缓存清除
        // clearAllExchangeOrderDetailsCache(); // 移除缓存清除
        
        // 8. 返回创建的订单信息
        return exchangeOrderMapper.selectExchangeOrderById(exchangeOrder.getId());
    }
    
    /**
     * 生成订单号
     */
    private String generateOrderSn() {
        return "EX" + System.currentTimeMillis() + String.format("%04d", (int)(Math.random() * 10000));
    }
}
